package com.easybuy.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easybuy.entity.Product;
import com.easybuy.service.ProductService;
import com.easybuy.service.impl.ProductServiceImpl;
import com.easybuy.util.PageUtil;

public class AdminProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ProductService productService = new ProductServiceImpl();
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null) {
			switch (action) {
			case "index":
				index(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}

	/**
	 * 跳转到商品列表页面，要分页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int currPageNo = 1;
		int pageSize = 6;
		
		String paramCurrPageNo = request.getParameter("currPage");
		if (paramCurrPageNo != null && !"".equals(paramCurrPageNo)) {
			currPageNo = Integer.parseInt(paramCurrPageNo);
		}
		
		List<Product> productList = productService.findList(currPageNo,pageSize);
		
		//总记录数
		int totalCount = productService.findCount();
	
		
		PageUtil<Product> pageUtil = new PageUtil<>();
		pageUtil.setCurrPage(currPageNo);
		pageUtil.setTotalCount(totalCount);
		pageUtil.setPageSize(pageSize);
		pageUtil.setList(productList);
		
		request.setAttribute("pageUtil", pageUtil);
		request.getRequestDispatcher("/backend/product/productList.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
